<?php

namespace App\Console\Commands;

use App\Activity;
use App\Order;
use App\Support\User;
use Illuminate\Console\Command;

class SendSms extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'sms:send';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'send sms';

	protected $user;

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct(User $user) {
		parent::__construct();
		$this->user = $user;
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle() {
		//读取没有发送的数据
		// $list = (new Order())->where('type', 0)->select('id', 'phone')->get();
		$list = (new Order())->where('id', 942)->select('id', 'map_id', 'phone', 'order_id')->get()->load('map');
		$activity_ids = [];
		foreach ($list as $key => $value) {
			array_push($activity_ids, $value->map->activity_id);
			//处理单条并更新订单状态
			$log = $this->handleItem($value);
			$this->info($log);
			if (!$log) {
				$this->error($value->phone . 'went wrong!');
				continue;
			}
			//发送短信
			$this->user->sendSms($value->phone, $log->unique);
			$this->info($value->phone . 'success');
		}
		$model = new Activity();
		$activity_ids = array_merge(array_unique($activity_ids));
		foreach ($activity_ids as $key => $value) {
			$activity = $model->findOrFail($value);
			if (!$activity->start_time) {
				$activity->start = 1;
				$activity->start_time = date('Y-m-d H:i:s');
				$activity->save();
			}
		}
		$this->info('success!');
	}

	private function handleItem($item) {
		$user_id = $this->user->register($item->phone);
		if (!$user_id) {
			$log = false;
			$item->type = 2;
		} else {
			$log = $item->sendLog()->create([
				'order_id' => $item->order_id,
				'send_id' => $user_id,
				'map_id' => $item->map_id,
				'products' => $item->map->activity->product,
				'unique' => uniqid() . substr($item->phone, -4),
				'win' => rand(1, 10),
				'create_time' => date('Y-m-d H:i'),
				'expore_time' => date('Y-m-d H:i', strtotime('+15 days')),
			]);
			$item->type = 1;
		}
		$item->send_time = date('Y-m-d H:i:s');
		$item->save();
		return $log;
	}
}
